import axios from 'axios'
import Vue from 'vue'

import Vuex from 'vuex'

Vue.use(Vuex)

const state = {
    count: 0,
    price: 999,
    movieList: []
}

const mutations = {
    increment(state) {
        state.count++
    },
    decrement(state, {
        n
    }) {
        state.price -= n
    },
    getMovieList(state, movieList) {
        state.movieList = movieList
    }

}

const actions = {
    incrementWait({
        commit
    }) {
        setTimeout(() => {
            commit('increment')
        }, 2000)
    },

    async getMovieList({
        commit
    }) {
        const result = await axios.get('https://pcw-api.iqiyi.com/search/recommend/list?channel_id=1&data_type=1&mode=11&page_id=2&ret_num=48&session=b9fd987164f6aa47fad266f57dffaa6a')
        commit('getMovieList', result.data.data.list)
    }

}

// 有时候需要从store中的state中派生一些状态，例如对列表进行过滤并计数等需要计算，就要用到getters -- 类似vue中的计算属性
// getter的返回值会根据它的依赖被缓存起来，且只有当它的依赖值发生改变才会被重新计算
const getters = {
    myMovieList(state) {
        // 数据是state派生出来的，所以getters中函数接收一个参数是state
        return state.movieList.filter((movie) => {
            return movie.albumName.length < 7 && movie.albumName.length > 3
        })
    },

    // 可以传参的getters
    yourMovieList(state) {
        // 计算属性在计算的时候，需要接受参数，则getters函数需要返回一个函数
        return ({
            start,
            end
        }) => {
            return state.movieList.filter((movie) => {
                return movie.albumName.length <= end && movie.albumName.length >= start
            })
        }
    }
}

export default new Vuex.Store({
    state,
    mutations,
    actions,
    getters
})